package com.cskaoyan.service;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.cskaoyan.util.LocalStorage;
import com.cskaoyan.util.TransactionUtil;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

/**
 * @author stone
 * @date 2023/03/19 21:13
 */
public class StorageServiceImpl implements StorageService {
    private LocalStorage storage = new LocalStorage();
    @Override
    public MarketStorage store(InputStream inputStream, long size, String contentType, String fileName) {
        String key = generateKey(fileName);
        storage.store(inputStream, size, contentType, key);

        String url = generateUrl(key);
        MarketStorage storageInfo = new MarketStorage();
        storageInfo.setName(fileName);
        storageInfo.setSize((int) size);
        storageInfo.setType(contentType);
        storageInfo.setKey(key);
        storageInfo.setUrl(url);
        this.add(storageInfo);

        return storageInfo;
    }

    @Override
    public int add(MarketStorage storageInfo) {
        Date now = new Date();
        storageInfo.setAddTime(now);
        storageInfo.setUpdateTime(now);
        MarketStorageMapper storageMapper = TransactionUtil.getMapper(MarketStorageMapper.class);
        int insert = storageMapper.insert(storageInfo);
        TransactionUtil.commit();
        return insert;
    }

    private String generateUrl(String key) {

        return "http://localhost:8083/wx/storage/fetch/" + key;
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);

        String key = UUID.randomUUID().toString().replaceAll("-","") + suffix;

        return key;
    }
}
